import { Decimal } from "decimal.js";
import dayjs from "dayjs";

// import { camelCase } from '@/utils'

// 模态框，获取选择型组件的远程数据
export const remoteData = {
  created() {
    this.getRemoteData();
  },
  methods: {
    getRemoteData() {
      // 级联下拉选，远程数据单独处理
      if (this.conf.compType === "cascader") {
        return;
      }
      // 动态数据
      if (this.conf.dataType === "dynamic") {
        if (!this.conf.props) return;

        if (this.conf.props.type === "dict") {
          // 字典数据
          if (!this.conf.props.dictCode) return;
        } else if (this.conf.props.type === "table") {
          // online表单数据
          if (
            !this.conf.props.tableId ||
            !this.conf.props.tableCode ||
            !this.conf.props.label ||
            !this.conf.props.value
          )
            return;
        } else if (this.conf.props.type === "custom") {
          // 自定义接口数据
          if (!this.conf.action) return;
        }
      }
    },
  },
};

// 动态数据绑定
export const dynamicDataType = {
  data() {
    return {
      dynamicTypeOption: [
        { label: "字典数据", value: "dict" },
        { label: "表数据", value: "table" },
        { label: "接口数据", value: "custom" },
      ],
      dictCodeList: [],
      tableCodeList: [],
      tableColumnList: [],
    };
  },
  created() {
    this.getTableList();
    this.getDictList();
  },
  mounted() {
    if (this.props.props && this.props.props.tableCode) {
      this.getTableColumnList(this.props.props.tableCode);
    }
    if (this.props.props === undefined) {
      this.props.props = {};
      this.props.props = Object.assign(
        {},
        {
          type: "dict",
          dictCode: "",
          tableId: "",
          tableCode: "",
          label: "label",
          value: "value",
        }
      );
      this.$forceUpdate();
    }
  },
  methods: {
    // 获取字典列表
    getDictList() {},
    // 获取表单列表
    getTableList() {},

    handleChangeTable(val) {
      this.props.props.tableId = this.tableCodeList.find(
        (i) => i.tableName === val
      )?.id;
      this.props.props.label = "";
      this.props.props.value = "";
      this.$forceUpdate();
      this.getTableColumnList();
    },

    getTableColumnList() {
      if (!this.props.props.tableCode) {
        this.tableColumnList = [];
        this.props.props.label = "";
        this.props.props.value = "";
        this.$forceUpdate();
        return;
      }
    },

    // 动态数据类型改变
    handleChangeDynamicType(val) {
      this.props.props.type = val;
      this.props.props.dictCode = "";
      this.props.props.tableCode = "";
      this.props.props.label = "";
      this.props.props.value = "";

      this.$forceUpdate();
    },
  },
};

export const changeId = {
  methods: {
    handlerChangeId(val) {
      const idArray = this.getFormId(this.props._id);
      console.log(idArray);
      if (idArray.includes(val)) {
        // 如果存在id相等，则提示
        this.$message.error("该ID已经存在，请修改");
        this.props.id = this.props._id;
      } else {
        this.props._id = val;
      }
    },
  },
};

/**
 * 关联字段配置
 */
export const fieldNameList = {
  props: {
    tableName: {
      type: String,
      default: "",
    },
    fieldNameList: {
      type: Array,
      default: function () {
        return [];
      },
    },
  },
  data() {
    return {
      subFormFieldNameList: [],
    };
  },
  watch: {
    // 绑定子表单修改
    "props.subTableName": {
      handler: function () {
        // this.handleChangeTableName()
        // console.log('333',val, oldVal, this.props.subTableName)
        this.getSubFormFieldNameList();
      },
    },
  },
  created() {
    this.getSubFormFieldNameList();
  },
  methods: {
    handleChangeField(val) {
      // 更改绑定字段时，自动更新字段名称
      if (this.props.customType === "subComp") {
        this.props.label = this.subFormFieldNameList.find(
          (i) => i.dbFieldName === val
        )?.dbFieldTxt;
      } else {
        this.props.label = this.fieldNameList.find(
          (i) => i.dbFieldName === val
        )?.dbFieldTxt;
      }
      this.$forceUpdate();
    },
    // 获取表单字段列表
    getSubFormFieldNameList() {
      this.subFormFieldNameList = [];
      if (this.props.customType === "subComp" && !this.props.subTableName) {
        console.log("未设置关联子表");
        return;
      }
      if (!this.props.subTableName) return;
    },
  },
};

/**
 * 公式函数mixin
 */
export const fnFromReview = {
  data() {
    return {
      fns: [],
    };
  },
  created() {
    this.getFns();
  },
  mounted() {
    this.$nextTick(() => {
      // 有值触发一次
      this.fns.forEach((element) => {
        element.fnArr.forEach((item) => {
          if (this.form[item]) {
            this.triggerFn(item);
          }
        });
      });
    });
  },
  methods: {
    // 初始化获取所有含有公式函数的表单
    getFns() {
      if (this.buildData) {
        this.fns = this.flattenFormJson(JSON.parse(this.buildData));
      } else {
        this.fns = this.flattenFormJson({ list: [...this.list] });
      }
    },
    // 公式触发器
    triggerFn(key) {
      let allTriggerArr = [];
      this.fns.forEach((element) => {
        allTriggerArr = [...allTriggerArr, ...element.fnArr];
      });
      const canTrigger = allTriggerArr.includes(key); // 是否能触发
      if (canTrigger) {
        // 求和
        window.SUM = function () {
          const array = [...arguments];
          return array
            .reduce((total, current) => Decimal(+total).add(Decimal(+current)))
            .toNumber();
        };
        // 求平均值
        window.AVERAGE = function () {
          const array = [...arguments];
          return (
            array
              .reduce((acc, curr) => Decimal(+acc).add(Decimal(+curr)))
              .toNumber() / array.length
          );
        };
        //加
        window.ADD = function () {
          const array = [...arguments];
          return array
            .reduce((total, current) => Decimal(+total).add(Decimal(+current)))
            .toNumber();
        };
        // 减
        window.SUBTRACT = function () {
          const array = [...arguments];
          return array
            .reduce((total, current) => Decimal(+total).sub(Decimal(+current)))
            .toNumber();
        };
        // 乘
        window.PRODUCT = function () {
          const array = [...arguments];
          return array
            .reduce((total, current) => Decimal(+total).mul(Decimal(+current)))
            .toNumber();
        };
        // 除
        window.MOD = function () {
          const array = [...arguments];
          return array
            .reduce((total, current) => Decimal(+total).div(Decimal(+current)))
            .toNumber();
        };
        // 大写金额
        (window.DEALBIGMONEY = function () {
          let money = +[...arguments][0];
          console.log(money);
          let fraction = ["角", "分"];
          let digit = [
            "零",
            "壹",
            "贰",
            "叁",
            "肆",
            "伍",
            "陆",
            "柒",
            "捌",
            "玖",
          ];
          let unit = [
            ["元", "万", "亿"],
            ["", "拾", "佰", "仟"],
          ];
          let head = money < 0 ? "欠" : "";
          money = Math.abs(money);
          let s = "";
          for (let i = 0; i < fraction.length; i++) {
            s += (
              digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]
            ).replace(/零./, "");
          }
          s = s || "整";
          money = Math.floor(money);
          for (let i = 0; i < unit[0].length && money > 0; i++) {
            let p = "";
            for (let j = 0; j < unit[1].length && money > 0; j++) {
              p = digit[money % 10] + unit[1][j] + p;
              money = Math.floor(money / 10);
            }
            s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;
          }
          return (
            head +
            s
              .replace(/(零.)*零元/, "元")
              .replace(/(零.)+/g, "零")
              .replace(/^整$/, "零元整")
          );
        }),
          // 账务日期时间差
          (window.ACCTTIMEDIFF = function () {
            // 两个小时算一天
            const array = [...arguments];
            const beginTime = array[0];
            const endTime = array[1];
            let diffDay = dayjs(endTime).diff(beginTime, "day");
            if (diffDay > 0) {
              const diffHour = dayjs(endTime).diff(beginTime, "hour");
              if (diffHour / 24 - diffDay > 2) {
                diffDay = diffDay + 1;
              }
            } else {
              const diffHour = dayjs(endTime).diff(beginTime, "hour");
              if (diffHour > 2) {
                diffDay = diffDay + 1;
              }
            }
            return diffDay;
          });
        window.fn$Form = { ...this.form };
        this.fns.forEach((item) => {
          if (item.fnArr.includes(key)) {
            const { id, $fn, fnText } = item;
            if ($fn) {
              let value = "";
              let fn = $fn.replaceAll("$[", "fn$Form.");
              fn = fn.replaceAll("]$", "");
              fn = "value = " + fn;
              eval(fn);
              if (!Number.isFinite(value) && !fnText.includes("DEALBIGMONEY")) {
                value = "";
              }
              this.$set(this.form, id, value);
              // 联动触发
              this.triggerFn(id);
            }
          }
        });
      }
    },
    // 获取函数公式表单
    flattenFormJson(obj, res = []) {
      res.push(obj);
      if (obj.columns && obj.columns.length) {
        for (const item of obj.columns) {
          this.flattenFormJson(item, res);
        }
      }
      if (obj.list && obj.list.length) {
        for (const item of obj.list) {
          this.flattenFormJson(item, res);
        }
      }
      return res.filter(
        (i) => Object.hasOwn(i, "fnText") && Object.hasOwn(i, "fnArr")
      );
    },
  },
};
